import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { useApi } from './useApi.js'
import { useDataStore } from './useDataStore.js'

/**
 * 关系管理Hook
 * 处理页面-分类、分类-项目、项目-分类等各种关联关系
 */
export function useRelationManager() {
  const api = useApi()
  const dataStore = useDataStore()
  
  // 选择状态
  const selectedPageId = ref(null)
  const selectedCategoryId = ref(null)
  const selectedCategoryIdForItem = ref(null)
  const selectedItemId = ref(null)
  const selectedItemToAdd = ref(null)
  const selectedItemToRelate = ref(null)
  const selectedCategoryToRelate = ref(null)
  
  // 关系数据
  const currentPageCategories = ref([])
  const currentCategoryItems = ref([])
  const availableItemsForCategory = ref([])
  const currentItemCategories = ref([])
  const availableCategoriesForItem = ref([])
  const currentRelatedItems = ref([])
  
  // 新建时的临时关联关系存储
  const tempCategoryRelations = ref({
    pages: [],
    items: []
  })
  
  const tempItemRelations = ref({
    categories: []
  })
  
  /**
   * 更新当前分类的项目列表
   */
  const updateCurrentCategoryItems = async () => {
    if (!dataStore.currentCategory?.value?.id) return
    
    try {
      const categoryId = dataStore.currentCategory.value.id
      // 从层级数据中获取当前分类的项目
      const categoryItems = []
      dataStore.hierarchyData.value.forEach(page => {
        page.categories?.forEach(category => {
          if (category.id === categoryId) {
            categoryItems.push(...(category.items || []))
          }
        })
      })
      currentCategoryItems.value = categoryItems
      
      // 更新可用项目列表（排除已关联的项目）
      const currentItemIds = categoryItems.map(item => item.id)
      availableItemsForCategory.value = dataStore.items.value.filter(
        item => !currentItemIds.includes(item.id)
      )
    } catch (error) {
      console.error('更新分类项目列表失败:', error)
    }
  }
  
  /**
   * 获取当前项目的分类信息
   * @param {number} itemId - 项目ID
   */
  const fetchCurrentItemCategories = async (itemId) => {
    if (!itemId) return
    
    try {
      const itemCategories = []
      dataStore.hierarchyData.value.forEach(page => {
        page.categories?.forEach(category => {
          if (category.items?.some(item => item.id === itemId)) {
            itemCategories.push(category)
          }
        })
      })
      currentItemCategories.value = itemCategories
    } catch (error) {
      console.error('获取项目分类信息失败:', error)
    }
  }
  
  /**
   * 更新当前项目的分类列表
   */
  const updateCurrentItemCategories = () => {
    const itemId = dataStore.itemForm?.id
    if (!itemId) return
    
    fetchCurrentItemCategories(itemId)
  }
  
  /**
   * 更新项目可用分类列表
   */
  const updateAvailableCategoriesForItem = () => {
    const currentCategoryIds = currentItemCategories.value.map(c => c.id)
    availableCategoriesForItem.value = dataStore.categories.value.filter(
      c => !currentCategoryIds.includes(c.id)
    )
  }
  
  /**
   * 为项目添加分类关联
   */
  const addCategoryToItem = async () => {
    const itemId = dataStore.itemForm?.id
    const categoryId = selectedCategoryToRelate.value
    if (!categoryId) return
    
    // 如果是新建项目（没有itemId），添加到临时关联关系中
    if (!itemId) {
      if (!tempItemRelations.value.categories.includes(categoryId)) {
        tempItemRelations.value.categories.push(categoryId)
        ElMessage.success('分类关联已添加，将在保存项目后生效')
      } else {
        ElMessage.warning('该分类已在关联列表中')
      }
      selectedCategoryToRelate.value = null
      return
    }
    
    // 如果是编辑项目，先刷新数据再检查关系是否已存在，然后建立关联
    await fetchCurrentItemCategories(itemId)
    
    // 检查关系是否已存在
    const isAlreadyRelated = currentItemCategories.value.some(
      category => category.id === categoryId
    )
    if (isAlreadyRelated) {
      ElMessage.warning('该分类已与项目关联')
      selectedCategoryToRelate.value = null
      return
    }
    
    try {
      await dataStore.manageItemCategoryRelation(categoryId, itemId, 'add')
      selectedCategoryToRelate.value = null
      // 刷新当前项目的分类数据
      await new Promise(resolve => setTimeout(resolve, 100))
      await fetchCurrentItemCategories(itemId)
      updateAvailableCategoriesForItem()
      ElMessage.success('关系添加成功')
    } catch (error) {
      ElMessage.error('关系添加失败')
      console.error('添加项目分类关系失败:', error)
    }
  }
  
  /**
   * 移除项目的分类关联
   * @param {number} itemId - 项目ID
   * @param {number} categoryId - 分类ID
   */
  const removeCategoryFromItem = async (itemId, categoryId) => {
    // 如果只传了一个参数，说明是旧的调用方式，categoryId实际是第一个参数
    if (categoryId === undefined) {
      categoryId = itemId
      itemId = dataStore.itemForm?.id
    }
    
    // 如果是新建项目，从临时关联关系中移除
    if (!itemId) {
      const index = tempItemRelations.value.categories.indexOf(categoryId)
      if (index > -1) {
        tempItemRelations.value.categories.splice(index, 1)
        ElMessage.success('分类关联已移除')
      }
      return
    }
    
    // 如果是编辑项目，直接移除关联
    try {
      await dataStore.manageItemCategoryRelation(categoryId, itemId, 'remove')
      // 刷新当前项目的分类数据
      await new Promise(resolve => setTimeout(resolve, 100))
      await fetchCurrentItemCategories(itemId)
      updateAvailableCategoriesForItem()
      ElMessage.success('关系移除成功')
    } catch (error) {
      ElMessage.error('关系移除失败')
      console.error('移除项目分类关系失败:', error)
    }
  }
  
  /**
   * 获取临时关联的分类列表（用于新建项目时显示）
   */
  const getTempRelatedCategoriesForItem = () => {
    return dataStore.categories.value.filter(
      c => tempItemRelations.value.categories.includes(c.id)
    )
  }
  
  /**
   * 清空所有临时关联关系
   */
  const clearTempRelations = () => {
    tempCategoryRelations.value = { pages: [], items: [] }
    tempItemRelations.value = { categories: [] }
    currentRelatedItems.value = []
    selectedItemToRelate.value = null
    selectedCategoryToRelate.value = null
  }
  
  /**
   * 重置所有选择状态
   */
  const resetSelections = () => {
    selectedPageId.value = null
    selectedCategoryId.value = null
    selectedCategoryIdForItem.value = null
    selectedItemId.value = null
    selectedItemToAdd.value = null
    selectedItemToRelate.value = null
    selectedCategoryToRelate.value = null
  }
  
  return {
    // 选择状态
    selectedPageId,
    selectedCategoryId,
    selectedCategoryIdForItem,
    selectedItemId,
    selectedItemToAdd,
    selectedItemToRelate,
    selectedCategoryToRelate,
    
    // 关系数据
    currentPageCategories,
    currentCategoryItems,
    availableItemsForCategory,
    currentItemCategories,
    availableCategoriesForItem,
    currentRelatedItems,
    
    // 临时关联关系
    tempCategoryRelations,
    tempItemRelations,
    
    // 方法
    updateCurrentCategoryItems,
    fetchCurrentItemCategories,
    updateCurrentItemCategories,
    updateAvailableCategoriesForItem,
    addCategoryToItem,
    removeCategoryFromItem,
    getTempRelatedCategoriesForItem,
    clearTempRelations,
    resetSelections
  }
}